/* eslint-disable react/no-access-state-in-setstate */
/* eslint-disable react/prop-types */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/index';
import { Message, ConfigProvider } from '@teamix/ui';
import { Layout } from '@alife/devops-ui';
import { getIntroPointState, setIntroPointState, getProjectServices } from 'api';
import CreateProjectModal from 'components/createProjectModal/loadable';
import { pages } from './interface';
import ProjectNav from './nav';
import { track, register } from 'utils/track';
import utils from 'utils';
import exceed from 'utils/apimap';
import { navigateOpen } from 'utils/router';
import { getFeature } from 'utils/features';
import TooLargeTip from './tooLargeTip';
// import { Assistant } from '@alife/teamix-assistant';
import Assistant from 'components/libraryInsideGuide';
import initHelp from 'utils/initNavigation/initHelp';
import './index.scss';

const { organization_id } = window.FORCE.organization;

const sensitive_info_detection = 'sensitive_info_detection';
const dependency_analysis = 'dependency_analysis';
const pinpoint_detection = 'pinpoint_detection';
const checkServiceSwitchKeys = [sensitive_info_detection, dependency_analysis, pinpoint_detection];

class Root extends Component {
  constructor(props) {
    super(props);
    const propsCount =
      Number(window.localStorage.getItem(`guide-${organization_id}-propsCount`)) || 0;
    this.state = {
      createProjectModalShow: false,
      guideVisible: false,
      guideStatus: { step: 0, active: true, status: false },
      guidePropsCount: propsCount,
      // guide: JSON.parse(window.localStorage.getItem('guide')) || {},
      isStick: window.localStorage.isSidebarStick === 'true',
    };
    this.layoutOptions = {
      noPaddings: ['projectFiles', 'projectMergeRequestDetail', 'projectCommitDetail'],
    };
  }

  componentDidMount() {
    this.props.getProjectInfo((projectInfo) => {
      // 用户进入demo库10s后弹引导弹窗
      if (projectInfo && projectInfo.demo_project) {
        // projectInfo.demo_project
        this.demoRepoTimeout = setTimeout(() => {
          // 弹窗前再次验证是否还在demo库
          if (
            window.FORCE.pathResource.id &&
            Number(window.FORCE.pathResource.id) === projectInfo.id
          ) {
            this.getIfShowCreateYourProjectPop();
            // 弹窗出现后，标记不再出现
            this.setIfShowCreateYourProjectPop();
          }
        }, 5000);
      }

      // 进入库后如果是首次创建库，出现引导弹窗
      this.getIfShowCreateRepoSuccessPop();
    }, true);
    // guide 引导库内安全扫描
    // this.getServiceInfo();
    // 将 projectId 注册为gta的属性
    register('codeup_projectid', window.FORCE.pathResource.id);
    // 标记已进入库，用于window.TB_NAVIGATION.Dock.showDockGuide调用
    if (!utils.getCachedData('group_or_repo_visited')) {
      utils.setCachedData('group_or_repo_visited', true);
    }
    // this.newGuideCodeUP(this.state.guide);
    this.guideCodeupHander();
    this.props.getMirrorSyncSettings();
    this.mirrorSync = setInterval(() => {
      this.props.getLastMirrorSyncRecord(() => {
        clearInterval(this.mirrorSync);
      });
    }, 2000);
    this.props.genwatermark();
    this.fetchWiki();
  }

  fetchWiki = () => {
    const { pathResource } = window.FORCE;
    exceed
      .fetch({
        api: 'uiless.getAllExtension',
        params: {
          organizationId: window.UILessConfig.orgId,
          objectId: pathResource.id,
        },
        data: {
          objectType: 'Repository',
          identifier: 'app_for_code',
          isRecordVisit: 'true',
        },
      })
      .then((res) => {
        if (res.success && res.result && res.result[0]) {
          this.props.updateData({
            wikiEnable: res.result[0].enabled,
          });
        }
      });
  };

  guideCodeupHander() {
    this.guideCodeup = setInterval(() => {
      const guide = JSON.parse(window.localStorage.getItem(`guide-${organization_id}`));
      const neglectUserId =
        window.localStorage.getItem(`guideNeglectGroup-${organization_id}`) || '';
      const guideUserid = window.FORCE.user.id;
      const userflag = neglectUserId.indexOf(guideUserid) > -1;
      const { pageInfo } = this.props.root;
      if (!guide) return false;
      if (guide && guide.id === pageInfo.pathResource.id && guide.setp === -1 && !userflag) {
        clearInterval(this.guideCodeup);
        this.setState({ guideVisible: true });
      } else if (guide && guide.id === pageInfo.pathResource.id && guide.setp === 0 && !userflag) {
        clearInterval(this.guideCodeup);
        this.setState({
          guideStatus: { step: 0, active: true, status: guide.status },
          guideVisible: true,
          guidePropsCount: this.state.guidePropsCount || 1,
        });
        guide.status &&
          setTimeout(() => {
            this.setState({
              guideStatus: { step: 1, active: true, status: false },
              guideVisible: true,
              guidePropsCount: this.state.guidePropsCount || 1,
            });
          }, 1500);
      } else if (!userflag) {
        clearInterval(this.guideCodeup);
        this.newGuideCodeUP(guide, pageInfo.pathResource.id);
      }
    }, 1500);
  }

  checkServiceInfo = (serviceData) => {
    for (const key of checkServiceSwitchKeys) {
      if (serviceData[key] && serviceData[key].enabled) {
        return true;
      }
    }
    return false;
  };

  newGuideCodeUP(guide, id) {
    if (guide.id === id && guide.setp === 1) {
      this.setState({
        guideVisible: true,
        guidePropsCount: this.state.guidePropsCount || 1,
        guideStatus: { step: guide.setp, active: true, status: false },
      });
      this.guideBranch = setInterval(() => {
        exceed
          .fetch({
            api: 'projects.single.get',
            params: { id: guide.id },
          })
          .then((res) => {
            if (res.default_branch) {
              clearInterval(this.guideBranch);
              this.setState({ guideStatus: { step: 1, status: true, active: true } }, () => {
                const guideValue = JSON.stringify({ setp: 2, status: false, id: guide.id });
                window.localStorage.setItem(`guide-${organization_id}`, guideValue);
                setTimeout(() => {
                  this.guideCodeupHander();
                  this.setState({
                    guideVisible: true,
                    guidePropsCount: this.state.guidePropsCount || 1,
                    guideStatus: { step: 2, active: true, status: false },
                  });
                  track({
                    action: 'at_step_flow',
                    page: 'repo-guidance',
                  });
                }, 1500);
              });
            }
          });
      }, 3000);
    } else if (guide.id === id && guide.setp === 2) {
      this.setState({
        guideVisible: true,
        guidePropsCount: this.state.guidePropsCount || 1,
        guideStatus: { step: guide.setp, active: true, status: false },
      });
      // 流水线
      this.props.codeupGuideFlowActive(true);
      if (getFeature('module_enable.repository.flow')) {
        this.guideFlow = setInterval(() => {
          exceed
            .fetch({
              api: 'project.pipelines',
              params: { projectId: guide.id },
            })
            .then((res) => {
              if (res.length > 1) {
                clearInterval(this.guideFlow);
                this.setState({ guideStatus: { step: 2, status: true, active: true } }, () => {
                  const guideValue = JSON.stringify({ setp: 3, status: false, id: guide.id });
                  window.localStorage.setItem(`guide-${organization_id}`, guideValue);
                  // this.getServiceInfo(); // 库内安全扫描
                  this.props.codeupGuideFlowActive(false);
                  setTimeout(() => {
                    this.guideCodeupHander();
                    this.setState({
                      guideVisible: true,
                      guidePropsCount: this.state.guidePropsCount || 1,
                      guideStatus: { step: 3, active: true, status: false },
                    });
                    track({
                      action: 'at_step_scan',
                      page: 'repo-guidance',
                    });
                  }, 1500);
                });
              }
            });
        }, 3000);
      }
    } else if (guide.id === id && guide.setp === 3) {
      this.setState({
        guideVisible: true,
        guidePropsCount: this.state.guidePropsCount || 1,
        guideStatus: { step: guide.setp, active: true, status: false },
      });
      this.props.codeupGuideSafetyActive(true);
      this.Safety = setInterval(() => {
        getProjectServices()
          .then((result) => {
            const serviceData = result.integration_service_setting || {};
            const showSensitiveInfo = !this.checkServiceInfo(serviceData);
            if (!showSensitiveInfo) {
              // true 没有开启安全检查，false 开启
              clearInterval(this.Safety);
              this.props.codeupGuideSafetyActive(false);
              this.setState(
                {
                  guideVisible: true,
                  guidePropsCount: this.state.guidePropsCount || 1,
                  guideStatus: { step: guide.setp, active: true, status: true },
                },
                () => {
                  const guideValue = JSON.stringify({ setp: 4, status: false, id: guide.id });
                  window.localStorage.setItem(`guide-${organization_id}`, guideValue);
                },
              );
              setTimeout(() => {
                this.guideCodeupHander();
                this.setState({
                  guideVisible: true,
                  guidePropsCount: this.state.guidePropsCount || 1,
                  guideStatus: { step: 4, active: true, status: false },
                });
                track({
                  action: 'at_step_mr',
                  page: 'repo-guidance',
                });
              }, 1500);
            }
          })
          .catch((err) => {
            console.error(err);
          });
      }, 3000);
      // if (this.state.showSensitiveInfo === false) {
      //   this.setState({
      //     guideVisible: true,
      //     guidePropsCount: 1,
      //     guideStatus: { step: guide.setp, active: true, status: true },
      //   }, () => {
      //     const guideValue = JSON.stringify({ setp: 4, status: false, id: guide.id });
      //     window.localStorage.setItem('guide', guideValue);
      //   });
      //   setTimeout(() => {
      //     this.guideCodeupHander();
      //     this.setState({
      //       guideVisible: true,
      //       guidePropsCount: 1,
      //       guideStatus: { step: 4, active: true, status: false },
      //     });
      //   }, 1500);
      // } else {
      //   this.setState({
      //     guideVisible: true,
      //     guidePropsCount: 1,
      //     guideStatus: { step: guide.setp, active: true, status: false },
      //   });
      // }
    } else if (guide.id === id && guide.setp === 4) {
      this.setState({
        guideVisible: true,
        guidePropsCount: this.state.guidePropsCount || 1,
        guideStatus: { step: guide.setp, active: true, status: false },
      });
      this.props.codeupGuideMergeActive(true);
      this.guidemerge = setInterval(() => {
        exceed
          .fetch({
            api: 'mr.state_count',
            data: {
              page: 1,
              state: 'all',
              search: '',
              order_by: 'updated_at',
              project_ids: guide.id,
            },
          })
          .then((res) => {
            if (res.all >= 1) {
              this.props.codeupGuideMergeActive(false);
              clearInterval(this.guidemerge);
              this.setState({ guideStatus: { step: guide.setp, active: true, status: true } });
              setTimeout(() => {
                track({
                  action: 'at_step_finish',
                  page: 'repo-guidance',
                });
                this.setState({
                  guideStatus: { step: guide.setp + 1, active: true, status: true },
                });
                window.localStorage.removeItem(`guide-${organization_id}`);
              }, 1500);
            }
          });
      }, 3000);
    }
  }

  componentDidUpdate(prevProps) {
    const { pageInfo } = this.props.root;
    const { pageInfo: prevPageInfo } = prevProps.root;

    // 切库的时候
    if (
      prevPageInfo.pathResource.type === 'PROJECT' &&
      pageInfo.pathResource.type === 'PROJECT' &&
      prevPageInfo.pathResource.id &&
      pageInfo.pathResource.id &&
      prevPageInfo.pathResource.id !== pageInfo.pathResource.id
    ) {
      this.props.resetData();
      this.props.getProjectInfo();
      this.fetchWiki();

      // 将 projectId 注册为gta的属性
      register('codeup_projectid', pageInfo.pathResource.id);
    }
    // const guide = JSON.parse(window.localStorage.getItem('guide') || '{}');
    // if (guide.id !== this.state.guide.id && guide.setp !== this.state.guide.setp) {
    //   this.newGuideCodeUP(this.state.guide);
    // }
  }

  componentWillUnmount() {
    // 清空数据
    this.props.resetData();

    // 干掉可能存在的新建库引导
    Message.hide();

    if (this.demoRepoTimeout) {
      clearTimeout(this.demoRepoTimeout);
    }
    if (this.guideBranch) {
      clearInterval(this.guideBranch);
    }
    if (this.guideFlow) {
      clearInterval(this.guideFlow);
    }
    if (this.guideCodeup) {
      clearInterval(this.guideCodeup);
    }
    if (this.Safety) {
      clearInterval(this.Safety);
    }
    if (this.guidemerge) {
      clearInterval(this.guidemerge);
    }
    if (this.mirrorSync) {
      clearInterval(this.mirrorSync);
    }

    initHelp({
      showGuide: false,
    });
  }

  getIfShowCreateYourProjectPop = () => {
    const { pageInfo } = this.props.root;
    if (!pageInfo.pathResource.id) {
      return;
    }
    getIntroPointState('create_your_project_pop', {
      projectId: pageInfo.pathResource.id,
    })
      .then((result) => {
        if (result.state) {
          const guideValue = JSON.stringify({
            setp: -1,
            status: false,
            id: pageInfo.pathResource.id,
            nextSetp: 0,
          });
          window.localStorage.setItem(`guide-${organization_id}`, guideValue);
          this.setState({ guideVisible: true });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  jumpDoc = (item) => {
    track({
      action: item.action,
      page: 'Dialog-New Repo Guidance',
    });
    navigateOpen(item.link, '_blank');
  };

  getIfShowCreateRepoSuccessPop = () => {
    const { pageInfo } = this.props.root;
    getIntroPointState('first_repo_pop', {
      projectId: pageInfo.pathResource.id,
    })
      .then((result) => {
        if (result.state) {
          this.setIfShowCreateRepoSuccessPop();
          // 22222
          const guideValue = JSON.stringify({
            setp: 1,
            status: false,
            id: pageInfo.pathResource.id,
            nextSetp: 1,
          });
          window.localStorage.setItem(`guide-${organization_id}`, guideValue);
          this.setState({
            guideVisible: true,
            guidePropsCount: this.state.guidePropsCount || 1,
            guideStatus: { step: 1, active: true, status: false },
          });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  setIfShowCreateYourProjectPop = () => {
    const { pageInfo } = this.props.root;
    if (!pageInfo.pathResource.id) {
      return;
    }
    setIntroPointState('create_your_project_pop', {
      projectId: pageInfo.pathResource.id,
    })
      .then(() => {})
      .catch((err) => {
        console.error(err);
      });
  };

  setIfShowCreateRepoSuccessPop = () => {
    const { pageInfo } = this.props.root;
    setIntroPointState('first_repo_pop', {
      projectId: pageInfo.pathResource.id,
    })
      .then(() => {})
      .catch((err) => {
        console.error(err);
      });
  };

  renderMain = () => {
    const { pageInfo, updating } = this.props.root;
    const { isStick } = this.state;
    const { assetsName, pathResource = {} } = pageInfo;
    const LoadablePage = pages[assetsName];
    if (LoadablePage && !updating) {
      // timer isFromStartedToOther 传入projectFile，重新导入时用到
      return (
        <ConfigProvider prefix="yx-">
          <Layout
            className={isStick ? 'has-stick' : 'no-stick'}
            fullPage
            noPadding={this.layoutOptions.noPaddings.includes(assetsName)}
          >
            <TooLargeTip pageInfo={pageInfo} />
            <LoadablePage
              repoSize={pathResource.repoSize}
              timer={this.timer}
              isFromStartedToOther={this.isFromStartedToOther}
              getMirrorSyncSettings={this.props.getMirrorSyncSettings}
              updateOverViewData={this.props.updateData}
              isStick={isStick}
              onSidebarChange={this.onSidebarChange}
            />
          </Layout>
        </ConfigProvider>
      );
    } else {
      return null;
    }
  };

  onChangeStep = (step) => {
    switch (step) {
      case 'mr':
        this.props.codeupGuideFlowActive(false);
        this.props.codeupGuideSafetyActive(false);
        this.props.codeupGuideMergeActive(true);
        break;
      case 'scan':
        this.props.codeupGuideFlowActive(false);
        this.props.codeupGuideSafetyActive(true);
        this.props.codeupGuideMergeActive(false);
        break;
      case 'flow':
        this.props.codeupGuideFlowActive(true);
        this.props.codeupGuideSafetyActive(false);
        this.props.codeupGuideMergeActive(false);
        break;
      default:
        this.props.codeupGuideFlowActive(false);
        this.props.codeupGuideSafetyActive(false);
        this.props.codeupGuideMergeActive(false);
        break;
    }
  };

  onSidebarChange = (isStick) => {
    this.setState({
      isStick,
    });
  };

  render() {
    const { createProjectModalShow, guideVisible, guideStatus, guidePropsCount } = this.state;
    const { pageInfo } = this.props.root;
    const showWiki = this.props?.project?.root.wikiEnable;
    return (
      // <div className="project-layout-wrapper">
      <div>
        <ProjectNav {...this.props} showWiki={showWiki} onSidebarChange={this.onSidebarChange} />
        {/* <div className="project-fix-tab">
          <ProjectTab {...this.props} />
        </div> */}
        {this.renderMain()}
        {guideVisible && (
          <Assistant
            guide="2"
            guideStatus={guideStatus}
            guidePropsCount={guidePropsCount}
            onChangePropsCount={(propsCount) => {
              window.localStorage.setItem(`guide-${organization_id}-propsCount`, propsCount);
            }}
            guideCreateProject={() => {
              this.setIfShowCreateYourProjectPop();
              this.setState({ createProjectModalShow: true });
              track({ action: 'new_repo', page: 'Dialog-Demo Guidance' });
            }}
            onCloseGuide={() => {
              const guideNeglectValue =
                window.localStorage.getItem(`guideNeglectGroup-${organization_id}`) || '';
              const guideNeglectContent = `${guideNeglectValue + window.FORCE.user.id},`;
              window.localStorage.setItem(
                `guideNeglectGroup-${organization_id}`,
                guideNeglectContent,
              );
              initHelp({
                showGuide: true,
              });
            }}
            track={(action, rest = {}) => {
              track({ action, page: 'repo-guidance', ...rest });
            }}
            onChangeStep={this.onChangeStep}
          />
        )}
        {createProjectModalShow && (
          <ConfigProvider prefix="yx-">
            <CreateProjectModal
              closeModal={() => {
                this.setState({
                  createProjectModalShow: false,
                });
              }}
              isModalOpen={createProjectModalShow}
              onCreateSuccess={() => {
                const guideValue = JSON.stringify({
                  setp: 0,
                  status: true,
                  id: pageInfo.pathResource.id,
                  nextSetp: 1,
                });
                window.localStorage.setItem(`guide-${organization_id}`, guideValue);
                track({
                  action: 'at_step_branch',
                  page: 'repo-guidance',
                });
                this.setState({ guideStatus: { step: 0, status: true, active: true } });
                this.props.updateData({
                  createRepositorySuccess: true,
                });
              }}
            />
          </ConfigProvider>
        )}
      </div>
    );
  }
}

export default connect(
  (state) => state,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
